<?php

namespace App\Http\Controllers\Backend\Setting;

use App\Constants\RedisKey;
use App\Events\SettingLogEvent;
use App\Http\Requests\Backend\Setting\SettingLoanRequest;
use App\Models\SettingConfig;
use App\Models\SettingLoan;
use App\Models\SettingLog;
use App\Http\Controllers\Controller;
use Composer\Cache;
use Illuminate\Support\Facades\Redis;

class SettingLoanController extends Controller
{
    use \App\Library\Traits\SettingLog;
    const SETTING_TABLE = "setting_loan";
    public function __construct()
    {
        $this->middleware('auth:backend');
        $this->user = auth('backend')->user();
    }

    //获取
    public function getLoans(){
        $settingLoan = new SettingLoan();
        $settingLoan->setConnection('backend');
        $SettingConfig = new SettingConfig();
        $SettingConfig->setConnection('backend');
        $loanInfo =$settingLoan->select('id','blacklist_time','loan_range','period_range','receipt_time_one','receipt_time_two')->first();
        $config = $SettingConfig->select('home_image_time')->first();
        $loanInfo['home_image_time'] = $config['home_image_time'];
        return success($loanInfo);
    }

    //设置配置信息
    public function setLoans(SettingLoanRequest $request,$id){
        $data = $request->only(['blacklist_time','loan_range','period_range','receipt_time_one','receipt_time_two','home_image_time']);

        //home_image_time实在setting_config表中的
        if(isset($data['home_image_time'])){
            //保存在setting_config表中
            $SettingConfig = new SettingConfig();
            $SettingConfig->setConnection('backend');
            $config = $SettingConfig->select('id')->first();
            if(empty($config["id"])){
                $result = SettingConfig::where("id",$config['id'])->create(['home_image_time'=>$data['home_image_time']]);
                $this->setting_log($this->user->id,'setting_config',$result->id,SettingLog::LOG_UPDATE,$data);
            }else{
                SettingConfig::where("id",$config['id'])->update(['home_image_time'=>$data['home_image_time']]);
                $this->setting_log($this->user->id,'setting_config',$config['id'],SettingLog::LOG_UPDATE,$data);
            }
            \Cache::delete(RedisKey::SETTING_CONFIG);
            unset($data['home_image_time']);
        }
        if(isset($data['period_range'])){
            $period_range = json_decode($data['period_range'],true);
            sort($period_range);
            $data['period_range'] = json_encode($period_range);
        }
        $result = SettingLoan::where('id',$id)->update($data);
        \Cache::delete(RedisKey::SETTING_LOAN);
        $this->setting_log($this->user->id,self::SETTING_TABLE,$id,SettingLog::LOG_UPDATE,$data);
        return updated('');

    }
}
